package org.jeecg;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

public class GeoCoder {
    private static final String AMAP_API_URL = "https://restapi.amap.com/v3/geocode/geo";

    /**
     * 根据地址获取经纬度（使用高德地图API）
     * @param address 待查询的地址，如：北京市海淀区中关村
     * @param apiKey 高德地图API密钥
     * @return 包含经度和纬度的数组 [longitude, latitude]
     * @throws Exception 如果查询失败或解析异常
     */
    public static double[] getCoordinates(String address, String apiKey) throws Exception {
        // 参数校验
        if (address == null || address.trim().isEmpty()) {
            throw new IllegalArgumentException("地址不能为空");
        }
        if (apiKey == null || apiKey.trim().isEmpty()) {
            throw new IllegalArgumentException("API密钥不能为空");
        }

        // 构建请求URL
        URI uri = UriComponentsBuilder.fromHttpUrl(AMAP_API_URL)
                .queryParam("key", apiKey)
                .queryParam("address", address)
                .build().toUri();

        // 发送HTTP请求
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(uri, String.class);

        // 解析JSON响应
        ObjectMapper mapper = new ObjectMapper();
        com.fasterxml.jackson.databind.JsonNode root = mapper.readTree(response);

        // 检查状态码
        if (!"1".equals(root.path("status").asText())) {
            throw new Exception("高德API错误: " + root.path("info").asText());
        }

        // 检查是否有结果
        com.fasterxml.jackson.databind.JsonNode geocodes = root.path("geocodes");


        // 提取经纬度
        String location = geocodes.get(0).path("location").asText();
        String[] parts = location.split(",");
        if (parts.length != 2) {
            throw new Exception("解析经纬度失败: " + location);
        }

        return new double[]{
                Double.parseDouble(parts[0]),  // 经度
                Double.parseDouble(parts[1])   // 纬度
        };
    }

    // 使用示例
    public static void main(String[] args) {
        String apiKey = "fc48e1e74dfb98fbde22eaca6abcbf2d";  // 替换为实际的API密钥
        String address = "渝北区双龙湖街道凯歌一支路6号1幢1-3";

        try {
            double[] coordinates = getCoordinates(address, apiKey);
            System.out.printf("地址: %s\n经度: %.6f\n纬度: %.6f\n",
                    address, coordinates[0], coordinates[1]);
        } catch (Exception e) {
            System.err.println("获取经纬度失败: " + e.getMessage());
        }
    }
}
